package com.hqhsc.module.common.service;

import java.io.*;
import java.util.*;

import com.hqhsc.module.common.domain.*;
import com.hqhsc.module.common.domain.Enum;
import com.hqhsc.module.common.vo.MenuVo;
import com.hqhsc.module.init.service.InitService;
import com.hqhsc.module.login.domain.User;
import com.hqhsc.module.manage.activity.domain.Activity;
import com.hqhsc.module.manage.activity.domain.ActivityTemplet;
import com.hqhsc.module.manage.channel.domain.Channel;
import com.hqhsc.module.manage.system.domain.Org;
import com.hqhsc.utils.DateTimeUtil;
import com.hqhsc.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hqhsc.core.cache.CacheKey;
import com.hqhsc.module.common.dao.CommonDao;

@Service
public class CommonService {

	static Logger logger = LoggerFactory.getLogger(CommonService.class);

	@Autowired
	private CommonDao commonDao;
	@Autowired
	private ManageMemcacdedClient memcachedClient;
    @Autowired
    private Properties appProps;
    @Autowired
    private InitService initService;


    public void setUserMenu(User user , List<UserRole> user_role_list) {
        List<MenuVo> user_menu_list = this.getUserMenuList(user_role_list);
        user.setMenu_list(user_menu_list);
    }


    /**
     * 获取用户可操作的菜单列表
     * 一个用户可以对应多个角色
     * 这里获取的是用户所有的菜单，包括顶层菜单，以及其各层子菜单
     * @return
     */
    public List<MenuVo> getUserMenuList(List<UserRole> user_role_list) {
        List<MenuVo> user_menu_list = new ArrayList<MenuVo>();//用户菜单列表
        try {

            List<Menu> user_all_menu_list = new ArrayList<Menu>();//用户所有角色下的所有权限
            for(UserRole role : user_role_list) {
                long role_id = role.getRole_id();
                List<Menu> role_menu_list = this.getRoleMenuList(role_id);
                user_all_menu_list.addAll(role_menu_list);
            }

            for(Menu menu : user_all_menu_list) {
                if(menu.getPid() == 0) {//顶层菜单，需要组装子菜单
                    long menu_id = menu.getMenu_id();//顶层菜单id
                    for(MenuVo user_menu : user_menu_list) {
                        if(user_menu.getParent_menu().getMenu_id() == menu_id) {
                            break;
                        }
                    }

                    List<Menu> sub_menu_list = new ArrayList<Menu>();//子菜单
                    for(Menu sub_menu : user_all_menu_list) {
                        if(sub_menu.getPid() == menu_id) {
                            boolean isContain = false;
                            for(Menu tmp : sub_menu_list) {
                                if(sub_menu.getMenu_id() == tmp.getMenu_id()) {
                                    isContain = true;
                                    break;
                                }
                            }
                            if(!isContain) {//不包含，才将本次的sub_menu加入
                                sub_menu_list.add(sub_menu);
                            }
                        }
                    }
                    MenuVo menuVo = new MenuVo();
                    menuVo.setParent_menu(menu);
                    menuVo.setSub_menu(sub_menu_list);
                    menuVo.setSub_menu_size(sub_menu_list.size());

                    user_menu_list.add(menuVo);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user_menu_list;
    }



    /**
     * 获取单个角色对应的菜单
     * @param role_id
     * @return
     */
    public List<Menu> getRoleMenuList(long role_id) {
        String key = CacheKey.getRoleMenuListKey(role_id);
        List<Menu> role_menu_list = (List<Menu>)memcachedClient.get(key);
        if(role_menu_list == null) {
            role_menu_list = commonDao.getRoleMenuList(role_id);
            memcachedClient.set(key, 60*60, role_menu_list);
        }
        return role_menu_list;
    }

    /**
     * 获取用户角色列表，一个用户可能又多个角色
     * @param user_id
     * @return
     */
    public List<UserRole> getUserRoleList(long user_id) {
        String key = CacheKey.getUserRoleListKey(user_id);
        List<UserRole> user_role_list = (List<UserRole>)memcachedClient.get(key);
        if(user_role_list == null) {
            user_role_list = commonDao.getUserRoleList(user_id);
            memcachedClient.set(key, 60*60, user_role_list);
        }
        return user_role_list;
    }

    /**
     * 根据user_id获取用户
     * @param user_id
     * @return
     */
    public User getUserById(long user_id) {
        return this.commonDao.getUserById(user_id);
    }

    /**
     * 获取用户所在组织
     * @param user_id
     * @return
     */
//    public List<Org> getUserOrgList(long user_id) {
//        return this.commonDao.getUserOrgList(user_id);
//    }

    /**
     * 获取枚举表中某一类型的枚举值
     * @param fiel_name
     * @return
     */
    public List<Enum> getEnumFielList(String fiel_name) {
        List<Enum> enum_list = this.initService.getSysEnum();
        Map<String , List<Enum>> map = new HashMap<String, List<Enum>>();

        for(Enum en : enum_list) {
            List<Enum> tmp_list = new ArrayList<Enum>();
            if(map.get(en.getFiel_name()) != null) {
                tmp_list = map.get(en.getFiel_name());
            }
            tmp_list.add(en);
            map.put(en.getFiel_name() , tmp_list);
        }
        return map.get(fiel_name);
    }

    /**
     * 递归查找org_list下所有org，放到sub_org_list中返回
     * @param org_list
     * @param sub_org_list
     * @return
     */
//    private List<Org> getUserSubOrgList(List<Org> org_list , List<Org> sub_org_list) {
//        String all_orgid = "";
//        for(Org org : org_list) {
//            if(org.getOrg_type() < 14) {//小于14的，才会存在子门店
//                if("".equals(all_orgid)) {
//                    all_orgid = org.getOrg_id()+"";
//                } else {
//                    all_orgid = all_orgid + "," + org.getOrg_id();
//                }
//            }
//        }
//        //获取当前用户的所在组织的所有子门店
//        if(!"".equals(all_orgid)) {
//            List<Org> sub_tmp = this.commonDao.getUserSubOrgList(all_orgid);
//            sub_org_list.addAll(sub_tmp);
//            this.getUserSubOrgList(sub_tmp, sub_org_list);
//        }
//        return sub_org_list;
//    }

    /**
     * 获取用户可操作的所有门店列表
     * 树状结构关系
     * 如果用户所在某个门店，下面有管辖子门店，则子门店一并返回
     * @return
     */
//    public List<Org> getUserAllOrgList(long user_id) {
//        //首先，先要获取该用户所在组织，然后判断该组织是否有子门店
//        List<Org> org_list = this.commonDao.getUserOrgList(user_id);//用户当前所在门店
//        List<Org> sub_list = new ArrayList<Org>();
//        sub_list = this.getUserSubOrgList(org_list , sub_list);//用户所在门店的所有子门店
//
//        //整合所有该用户的门店，包括父门店、子门店
//        List<Org> user_all_org_list = new ArrayList<Org>();
//        user_all_org_list.addAll(org_list);
//        for(Org sub_org : sub_list) {
//            boolean flag = false;//是否有重复的
//            for(Org org : org_list) {
//                if(org.getOrg_id() == sub_org.getOrg_id()) {
//                    flag = true;
//                    break;
//                }
//            }
//            if(!flag) {
//                user_all_org_list.add(sub_org);
//            }
//        }
//
//        return user_all_org_list;
//    }

    /**
     * 根据用户、角色，获取该用户所有组织列表
     * @param user_id
     * @param role_id
     * @return
     */
    public List<Org> getUserRoleOrgList(long user_id , long role_id) {
        return this.commonDao.getUserRoleOrgList(user_id , role_id);
    }

    /**
     * 判断某用户是否是管理员
     * @param user_id
     * @return
     */
    public boolean isSysadmin(long user_id) {
        boolean isSysadmin = false;
        List<UserRole> user_role_list = this.getUserRoleList(user_id);
        for(UserRole user_role : user_role_list) {
            if(user_role.getRole_id() == 10000) {
                isSysadmin = true;
                break;
            }
        }
        return isSysadmin;
    }

    public String characterFormat(String str , String from_format , String to_format) {
        String return_str = null;
        try {
            if(str != null) {
                return_str = new String(str.getBytes(from_format),to_format);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return return_str;
    }

    public int checkIdCard(String certificate_no) {
        return this.commonDao.checkIdCard(certificate_no);
    }


    public String getContraceNo(long contrace_id) {
        String date = DateUtil.format(new Date() , "yyyyMMdd");
        return "HT"+date + contrace_id;
    }

    /**
     * 报表，分日、周、月、季、年
     * 根据不同类型，返回不同开始、结束时间
     * @param report_type
     * @return
     */
    public Map<String , Date> getBeginEndDate(String report_type) {
        String begin_str = null;
        String end_str = null;

        DateTimeUtil dateTimeUtil = new DateTimeUtil();
        if("day".equals(report_type)) {
            begin_str = DateUtil.format(new Date() , "yyyy-MM-dd")+" 00:00:00";
            end_str = DateUtil.format(new Date() , "yyyy-MM-dd")+" 23:59:59";
        }
        if("week".equals(report_type)) {
            begin_str = dateTimeUtil.getFirstDayOfWeek("CN")+" 00:00:00";
            end_str = dateTimeUtil.getLastDayOfWeek("CN")+" 23:59:59";
        }
        if("month".equals(report_type)) {
            begin_str = dateTimeUtil.getMonthFirstDay()+" 00:00:00";
            end_str = dateTimeUtil.getMonthLastDay()+" 23:59:59";
        }
        if("quarter".equals(report_type)) {
            Calendar c = Calendar.getInstance();
            String year = String.valueOf(dateTimeUtil.getYear());
            int currentMonth = c.get(Calendar.MONTH) + 1;
            try {
                if (currentMonth >= 1 && currentMonth <= 3) {
                    begin_str = year+"-01-01 00:00:00";
                    end_str = year+"-03-31 23:59:59";
                } else if (currentMonth >= 4 && currentMonth <= 6) {
                    begin_str = year+"-04-01 00:00:00";
                    end_str = year+"-06-30 23:59:59";
                } else if (currentMonth >= 7 && currentMonth <= 9) {
                    begin_str = year+"-07-01 00:00:00";
                    end_str = year+"-09-30 23:59:59";
                } else if (currentMonth >= 10 && currentMonth <= 12) {
                    begin_str = year+"-10-01 00:00:00";
                    end_str = year+"-12-31 23:59:59";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if("year".equals(report_type)) {
            String year = String.valueOf(dateTimeUtil.getYear());
            begin_str = year + "-01-01 00:00:00";
            end_str = year + "-12-31 23:59:59";
        }

        Date begin = null;
        Date end = null;
        if(begin_str != null && end_str != null) {
            try{
                begin = DateUtil.string2Date(begin_str , "yyyy-MM-dd HH:mm:ss");
                end = DateUtil.string2Date(end_str , "yyyy-MM-dd HH:mm:ss");
            } catch (Exception e) {
                logger.error(e.getMessage() , e);
            }
        }

        Map<String , Date> map = new HashMap<String, Date>();
        map.put("begin" , begin);
        map.put("end" , end);

        return map;
    }

    /**
     * 获取用户可使用的角色
     * 即用户当前角色，能够操作的其他角色
     * 一般为role_id>=自己role_id
     * @return
     */
    public List<Role> getUserCanUseRole(long user_role_id) {
        List<Role> sys_role_list = this.initService.getSysRole();
        List<Role> user_can_use_role_list = new ArrayList<Role>();
        for(Role sys_role : sys_role_list) {
            if(sys_role.getRole_id() >= user_role_id) {
                user_can_use_role_list.add(sys_role);
            }
        }
        return user_can_use_role_list;
    }

    /**
     * 获取系统互动信息
     * 缓存放30天
     * @param activity_id
     * @return
     */
    public Activity getSysActivityById(long activity_id) {
        String key = CacheKey.getActivityKey(activity_id);
        Activity activity = (Activity)this.memcachedClient.get(key);
        if(activity == null) {
            activity = this.commonDao.getSysActivityById(activity_id);
            if(activity != null) {
                String flow = activity.getFlow();
                String[] flow_args = flow.split("，");
                activity.setFlow_args(flow_args);
                this.memcachedClient.set(key , 30*24*60*60 , activity);
            }
        }
        return activity;
    }

    /**
     * 获取系统渠道信息
     * 缓存永久
     * @param channel_id
     * @return
     */
    public Channel getSysChannelById(long channel_id) {
        String key = CacheKey.getChannelKey(channel_id);
        Channel channel = (Channel)this.memcachedClient.get(key);
        if(channel == null) {
            channel = this.commonDao.getSysChannelById(channel_id);
            if(channel != null) {
                this.memcachedClient.set(key , 0 , channel);
            }
        }
        return channel;
    }

    public ActivityTemplet getActivityTempletById(long templet_id) {

        String key = CacheKey.getActivityTempletKey(templet_id);
        ActivityTemplet activityTemplet = (ActivityTemplet)this.memcachedClient.get(key);
        if(activityTemplet == null) {
            activityTemplet = this.commonDao.getActivityTemplet(templet_id);
            if(activityTemplet != null) {
                this.memcachedClient.set(key , 0 , activityTemplet);
            }
        }
        return activityTemplet;
    }
}
